//
//  Networking.swift
//  Skycar
//
//  Created by hxpp on 2018/6/11.
//  Copyright © 2018年 环球科技. All rights reserved.
//

import Foundation
import Alamofire
import HandyJSON

#if DEBUG
public func DDump(obj:Any?) {dump(obj)}
public let DNS = "http://www.hzmic.cn/index.php/app/"

#else

public func DDump(obj:Any?) {}
public let DNS = "http://www.hzmic.cn/index.php/app/"

#endif

func get() -> HTTPMethod {
    return HTTPMethod.get
}

public enum URL_PATH: String {
    case register = "user/user_deal" /// 注册 登录
    case content_data = "content/content_data"
    case avator_deal = "avator/avator_deal"
    case article_deal = "article/article_deal"
    case article_data = "article/article_data"
}

class Base_ViewModel: NSObject {}

public class Base_Model: HandyJSON {
    required public init() {}
}

class Net_base_data : Base_Model {
    var code : Int = 0
    var msg : String = ""
    var data : Any?
    var imgUrl : String = ""
}

class Net_base_data_any : Base_Model {
    var status: Int!
    var msg: String!
    var data:Any?
}

public extension HandyJSON {
    static public func networking(_ path:URL_PATH,m:HTTPMethod = .post,parameters:[String:Any],hud_block : (()->(MBProgressHUD))? = nil,complete:((_ obj:Any?)->())?, error : ((String,Int)->())?){
        
        var encoding : ParameterEncoding = URLEncoding.default
        
        if m == .post {
            encoding = JSONEncoding.default
        }
        var hud : MBProgressHUD?
        
        hud = hud_block?()
        
        hud?.show(animated: true)
        Alamofire.request(DNS + path.rawValue, method: m, parameters: parameters, encoding: encoding, headers: ["authToken": AccountCenter.token() ?? ""]).responseJSON { (response) in
            
            
            if let jsonValue = response.result.value {
                
                
                let repson = Net_base_data.deserialize(from: jsonValue as? [String : Any])
                
                DDump(obj: repson?.code)
                guard repson?.code == 1 else {
                    
                    if repson?.code == -1 {
                        
                        hud?.label.text = repson?.msg
                        hud?.hide(animated: true, afterDelay: 2)
                        
                        DispatchAfter(after: 2, handler: {
                            UIApplication.shared.keyWindow?.rootViewController = UIStoryboard.init(name: "Login", bundle: nil).instantiateInitialViewController()
                            UserDefaults.standard.set("", forKey: "user")
                            UserDefaults.standard.synchronize()
                        })
                        
                        return
                        
                    }
                    
                    DDump(obj: repson)
                    hud?.hide(animated: true)
                    error?((repson?.msg)!,1)
                    
                    return
                }
                
                hud?.hide(animated: true)
                
                if self == Net_base_data_any.self {
                    let repson_any = Net_base_data_any.deserialize(from: jsonValue as? [String : Any])
                    complete?(repson_any)
                }else if (self != Net_base_data.self) {
                    
                    if ((repson?.data as? [String:Any]) != nil) {
                        complete?(self.deserialize(from: (repson?.data as! [String:Any])))
                    }else if ((repson?.data as? [[String:Any]]) != nil) {
                        let datas = (repson?.data as! [[String:Any]])
                        var models : [Any] = []
                        for data in datas {
                            models.append(self.deserialize(from: data))
                        }
                        
                        if models.count == 0{
                            error?((repson?.msg)!,1)
                        }else {
                            complete?(models)
                        }
                        
                    }
                    
                }else {
                    complete?(repson)
                }
            }else {
                error?("网络错误~",0)
                hud?.hide(animated: true)
            }
        }
    }
    
    //MARK:表单提交 + body
    static public func networking_Form_body(_ path:URL_PATH,m:HTTPMethod = .post,parameters:[(String,Any)],hud_block : (()->(MBProgressHUD))? = nil,complete:((_ obj:Any?)->())?, error : ((String,Int)->())?, uploadProgress : @escaping (_ d : Double)->()){
        
        var encoding : ParameterEncoding = URLEncoding.default
        
        if m == .post {
            encoding = JSONEncoding.default
        }
        var hud : MBProgressHUD?
        hud = hud_block?()
        hud?.show(animated: true)
        
        let url = DNS + path.rawValue
        let headers = ["content-type":"multipart/form-data","authToken": AccountCenter.token() ?? ""]
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            
            //采用post表单上传
            for (a,b) in parameters {
                
                if a.contains("photo") {
                    
                    multipartFormData.append(b as! Data, withName: a, fileName: randomMD5() + ".png", mimeType: "image/jpeg")
                    
                    continue
                }
                
                if b is Data {
                    multipartFormData.append(b as! Data, withName: a)
                }
                
            }
            
        },to: url,method: .post,headers: headers, encodingCompletion: { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                //连接服务器成功后，对json的处理
                
                upload.responseJSON { response in
                    
                    if let jsonValue = response.result.value {
                        
                        
                        
                        let repson = Net_base_data.deserialize(from: jsonValue as? [String : Any])
                        
                        DDump(obj: repson?.code)
                        guard repson?.code == 1 else {
                            
                            if repson?.code == -1 {
                                
                                hud?.label.text = repson?.msg
                                hud?.hide(animated: true, afterDelay: 2)
                                
                                DispatchAfter(after: 2, handler: {
                                    UIApplication.shared.keyWindow?.rootViewController = UIStoryboard.init(name: "Login", bundle: nil).instantiateInitialViewController()
                                    UserDefaults.standard.set("", forKey: "user")
                                    UserDefaults.standard.synchronize()
                                })
                                
                                return
                                
                            }
                            
                            DDump(obj: repson)
                            hud?.hide(animated: true)
                            error?((repson?.msg)!,1)
                            
                            return
                        }
                        
                        hud?.hide(animated: true)
                        
                        if self == Net_base_data_any.self {
                            let repson_any = Net_base_data_any.deserialize(from: jsonValue as? [String : Any])
                            complete?(repson_any)
                        }else if (self != Net_base_data.self) {
                            
                            if ((repson?.data as? [String:Any]) != nil) {
                                complete?(self.deserialize(from: (repson?.data as! [String:Any])))
                            }else if ((repson?.data as? [[String:Any]]) != nil) {
                                let datas = (repson?.data as! [[String:Any]])
                                var models : [Any] = []
                                for data in datas {
                                    models.append(self.deserialize(from: data))
                                }
                                
                                if models.count == 0{
                                    error?((repson?.msg)!,1)
                                }else {
                                    complete?(models)
                                }
                                
                            }
                            
                        }else {
                            complete?(repson)
                        }
                    }else {
                        error?("网络错误~",0)
                        hud?.hide(animated: true)
                    }
                }
                
                upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
                    print("图片上传进度: \(progress.fractionCompleted)")
                    uploadProgress(progress.fractionCompleted)
                }
                
            case .failure(let encodingError):
                //打印连接失败原因
                hud?.hide(animated: true)
                error?("网络错误~",0)
                
            }
        })
    }
    
}


public func networking(_ path:URL_PATH,m:HTTPMethod = .post,parameters:[String:Any],hud_block : (()->(MBProgressHUD))? = nil,complete:((_ obj:Any?)->())?, error : ((String,Int)->())?){
    
    var hud : MBProgressHUD?
    hud = hud_block?()
    hud?.show(animated: true)
    Alamofire.request(DNS + path.rawValue, method: .post,parameters : parameters).validate(statusCode: 200..<300)
        .validate(contentType: ["text/html","text/plain"]).responseString { (response) in
            hud?.hide(animated: true)
            if response.result.isSuccess {
                complete?(response.result.value)
            }else {
                error?("网络错误!", 0)
            }
    }
}
